<template>
  <!-- 工序及定价 -->
  <div class="container">
    <div class="form-box">
      <el-form
        ref="formRef"
        :model="formData"
        label-width="120px"
        label-suffix="："
        :inline="true"
      >
        <el-form-item label="工序" prop="blurry">
          <el-select v-model="formData.blurry" placeholder="请选择工序" clearable filterable>
            <el-option
              v-for="item in options"
              :key="item"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item style="margin-left: 70px">
          <el-button type="primary" size="small" @click="querySub">
            查询
          </el-button>
          <el-button type="danger" size="small" @click="reset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <div class="operation">
        <el-button type="primary" size="small" @click="view('add')">
          新增
        </el-button>
        <el-button
          type="primary"
          size="small"
          :loading="exportLoading"
          @click="exportInspection"
        >
          导出
        </el-button>
      </div>
      <el-table
        v-loading="listLoading"
        :data="list"
        fit
        style="width: 100%"
        :max-height="tableHeight"
        border
      >
        <el-table-column label="工序" prop="name" align="center">
          <template #header>
            <div style="display: flex; align-items: center;justify-content: center" @click="handlePopoverVisibleChange('name')">
              <span>工序</span>
              <el-popover
                placement="bottom"
                width="200"
                trigger="manual"
                v-model="filterPopoverVisible"
              >
                <!-- 下拉框筛选输入 -->
                <el-select v-model="filterSearch.blurry" placeholder="请选择工序" clearable filterable>
                  <el-option
                    v-for="item in options"
                    :key="item"
                    :label="item.name"
                    :value="item.name"
                  />
                </el-select>
                <!-- 点击应用筛选 -->
                <div class="btn">
                  <el-button size="mini" @click="clearFilter">清除</el-button>
                  <el-button type="primary" size="mini" @click="applyFilter">确定</el-button>
                </div>
                <span class="iconfont icon-Rrl_s_049 icon-hover" slot="reference" :style="{ color: nameColor }"></span>
              </el-popover>
            </div>
          </template>
          <template #default="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="项次"
          prop="procedureConfigItems"
          align="center"
        >
          <template #header>
            <div style="display: flex; align-items: center;justify-content: center" @click="handlePopoverVisibleChange('procedureConfigItems')">
              <span>项次</span>
              <el-popover
                placement="bottom"
                width="200"
                trigger="manual"
                v-model="procedureConfigItemsVisible"
              >
                <!-- 下拉框筛选输入 -->
                <el-input
                  v-model="filterSearch.itemName"
                  placeholder="请输入项次"
                  size="small"
                  clearable
                />
                <!-- 点击应用筛选 -->
                <div class="btn">
                  <el-button size="mini" @click="clearFilter">清除</el-button>
                  <el-button type="primary" size="mini" @click="applyFilter">确定</el-button>
                </div>
                <span class="iconfont icon-Rrl_s_049 icon-hover" slot="reference" :style="{ color: procedureConfigItemsColor }"></span>
              </el-popover>
            </div>
          </template>
          <template slot-scope="scope">
            <div v-html="formatText(scope.row.procedureConfigItems)"></div>
          </template>
        </el-table-column>
        <el-table-column label="时间" prop="lastModifiedDate" align="center">
          <template #header>
            <div style="display: flex; align-items: center;justify-content: center" @click="handlePopoverVisibleChange('lastModifiedDate')">
              <span>时间</span>
              <el-popover
                placement="bottom"
                width="200"
                trigger="manual"
                v-model="lastModifiedDateVisible"
              >
                <!-- 下拉框筛选输入 -->
                <div class="picker">
                  <el-date-picker
                    v-model="filterSearch.lastModifiedDate"
                    type="date"
                    placeholder="请选择日期"
                    value-format="yyyy-MM-dd"
                  />
                </div>
                <!-- 点击应用筛选 -->
                <div class="btn">
                  <el-button size="mini" @click="clearFilter">清除</el-button>
                  <el-button type="primary" size="mini" @click="applyFilter">确定</el-button>
                </div>
                <span class="iconfont icon-Rrl_s_049 icon-hover" slot="reference" :style="{ color: lastModifiedDateColor }"></span>
              </el-popover>
            </div>
          </template>
          <template slot-scope="scope">
            {{ scope.row.lastModifiedDate }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          prop="requestCode"
          align="center"
          class="footer-box"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              :underline="false"
              @click="view('edit', scope.row)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        :current-page.sync="listQuery.page"
        :page-size.sync="listQuery.size"
        class="pagination-flex"
        @size-change="getdata"
        @current-change="getdata"
      />
    </div>
    <ProcessPricingDialog ref="processPricingDialogRef" @getdata="getdata" />
  </div>
</template>

<script>
import {
  getProcedureConfigs,
  getProcedureConfigPages,
  procedureConfigExport
} from '@/api/performanceStats'
import ProcessPricingDialog from './processPricingDialog.vue'
export default {
  // name: '',
  components: {
    ProcessPricingDialog
  },
  data() {
    return {
      filterPopoverVisible: false,
      lastModifiedDateVisible: false,
      procedureConfigItemsVisible: false,
      nameColor: '#909399',
      procedureConfigItemsColor: '#909399',
      lastModifiedDateColor: '#909399',
      formData: {},
      filterSearch: {},
      exportLoading: false,
      listLoading: false,
      list: [],
      total: 0,
      listQuery: {
        page: 1,
        size: 10
      },
      tableHeight: 0,
      subtractHeight: 180,
      options: []
    }
  },
  mounted() {
    this.getProcedureConfigs()
    this.getdata()
    window.addEventListener('resize', this.setHeight)
    this.$nextTick(() => {
      this.setHeight()
    })
  },
  activated() {
    this.setHeight()
    window.addEventListener('resize', this.setHeight)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setHeight)
  },
  deactivated() {
    window.removeEventListener('resize', this.setHeight)
  },
  methods: {
    async exportInspection() {
      this.exportLoading = true
      try {
        const response = await procedureConfigExport()
        const blob = new Blob([response.data], {
          type: 'application/vnd.ms-excel;charset=UTF-8'
        })

        // 处理 IE 特殊情况
        if ('msSaveOrOpenBlob' in navigator) {
          window.navigator.msSaveOrOpenBlob(blob, '工序及定价表.xls')
          return
        }

        const blobUrl = URL.createObjectURL(blob)
        const aLink = document.createElement('a')
        aLink.href = blobUrl
        aLink.setAttribute('download', '工序及定价表.xls') // 设置下载文件名称
        document.body.appendChild(aLink)
        aLink.click()
        document.body.removeChild(aLink) // 清理 DOM

        this.$message.success('导出成功！')
      } catch (error) {
        console.error('导出失败', error)
        this.$message.error('导出失败！')
      } finally {
        this.exportLoading = false // 确保在请求结束后更新加载状态
      }
    },
    async getdata(params = {}) {
      this.listLoading = true
      const { data } = await getProcedureConfigPages({
        ...this.listQuery,
        ...this.formData,
        ...this.filterSearch,
        ...params
      })
      this.list = data?.data?.content || []
      this.total = data?.data?.totalElements
      this.listLoading = false
    },
    getProcedureConfigs() {
      const query = {
        craftCode: 'GY001'
      }
      getProcedureConfigs(query).then((res) => {
        if (res.data && res.data.code === 200) {
          this.options = res.data.data
        }
      })
    },
    addInfo() {},
    view(type, row) {
      this.$refs.processPricingDialogRef.open(type, row)
    },
    setHeight() {
      const bodyHeight = document.body.clientHeight
      this.tableHeight = bodyHeight - this.subtractHeight
    },
    reset() {
      this.formData = {}
      this.listQuery.page = 1
      this.listQuery.size = 10
      this.filterSearch = {}
      this.getdata()
    },
    querySub() {
      this.getdata()
    },
    procedureConfigItems(info) {
      const result = info?.flat().map((i) => `${i.name} ${i.quantity} ${i.price}`)
      return result
    },
    formatText(items) {
      const itemTexts = this.procedureConfigItems([items]) // 获取一维数组
      return itemTexts.join('<br>') // 将数组转为 HTML 字符串
    },
    visible() {
      this.filterPopoverVisible = false // 应用筛选后关闭弹出框
      this.lastModifiedDateVisible = false
      this.procedureConfigItemsVisible = false
    },
    color() {
      this.nameColor = '#909399'
      this.procedureConfigItemsColor = '#909399'
      this.lastModifiedDateColor = '#909399'
    },
    applyFilter() {
      this.visible()
      this.getdata()
    },
    clearFilter() {
      this.filterSearch = {} // 清除筛选条件
      this.visible()
      this.color()
      this.getdata()
    },
    handlePopoverVisibleChange(type) {
      const popoverStates = {
        lastModifiedDate: 'lastModifiedDateVisible',
        procedureConfigItems: 'procedureConfigItemsVisible',
        name: 'filterPopoverVisible',
      }
      // 首先检查当前状态
      const currentStateKey = popoverStates[type]
      const isVisible = this[currentStateKey]

      // 重置所有状态和颜色
      Object.keys(popoverStates).forEach(key => {
        this[popoverStates[key]] = false // 设置状态为 false
        this[`${key}Color`] = '#909399' // 重置颜色
      })

      // 切换当前类型的可见性
      this[currentStateKey] = !isVisible // 切换状态
      if (this[currentStateKey]) {
        this[`${type}Color`] ='#409EFF'
      }else{
        this[`${type}Color`] ='#909399'
      }
      // this[`${type}Color`] = this[currentStateKey] ? '#409EFF' : '#909399' // 根据状态设置颜色
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.form-box {
  margin-top: 16px;
}

.operation {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 6px 20px;
  background-color: #f0f2f5;
}

::v-deep .el-pagination {
  text-align: right;
  margin: 20px 30px 0 0;
}
.footer-box {
  padding: 0 10px;
}
.btn{
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 5px
}
.picker{
  ::v-deep .el-date-editor.el-input{
    width: 100%;
  }
}
/* 添加悬停效果 */
.icon-hover:hover {
  color: #409eff !important; /* 悬停时的颜色 */
}
</style>
